import serial
import time

# sudo usermod -aG dialout $USER
# source /opt/ros/humble/setup.bash
# source install/setup.bash
# 配置串口
serial_port = "/dev/ttyS3"  # 串口设备路径
baud_rate = 115200            # 波特率
timeout = 1                 # 读取超时时间（秒）

try:
    # 打开串口
    ser = serial.Serial(serial_port, baud_rate, timeout=timeout)
    print(f"Opened serial port: {serial_port} with baud rate: {baud_rate}")
    
    # 每 1000ms 发送一次数据
    while True:
        message = "hello\n"  # 发送的消息
        ser.write(message.encode())  # 编码并发送数据
        print(f"Sent: {message.strip()}")
        time.sleep(1)  # 等待 1000ms
except serial.SerialException as e:
    print(f"Error opening or using serial port: {e}")
except KeyboardInterrupt:
    print("Program interrupted by user.")
finally:
    if 'ser' in locals() and ser.is_open:
        ser.close()  # 关闭串口
        print("Serial port closed.")
